<script setup lang="ts">
import { PAGING } from '@/constant'
import type { TableColumn, UserQueryListParams, UserQueryListResult, CustomDialogInstance } from '@/types'
import { Search } from '@element-plus/icons-vue'
import { loadEnterpriseOfReportAll } from '@/api/modules/sysDictionaryEnco'
import { loadSelectedEnterpriseOfReportUser, saveReportUserSubsidiary } from '@/api/modules/reportUserSubsidiary'

const dialogRef = ref<CustomDialogInstance>()
const defaultPagingParams: UserQueryListParams = {
  ...PAGING.PARAMS,
  userName: '',
}
const [total, setTotal] = useState<number>(0)
const loading = ref(false)
const userName = ref('')
const [userList, setUserList] = useState<
  UserQueryListResult[]
>([])
const column: TableColumn<UserQueryListResult>[] = [
  {
    key: uuid(),
    label: '用户名',
    prop: 'userName',
  },
  {
    key: uuid(),
    label: '登录账号',
    prop: 'loginName',
  },
  {
    key: uuid(),
    label: '角色',
    prop: 'roleName',
  },
  {
    key: uuid(),
    label: '部门',
    prop: 'departmentalName',
  },
  {
    key: uuid(),
    label: '所属企业',
    prop: 'tenantName',
  },
  {
    key: uuid(),
    label: '邮箱',
    prop: 'email',
  },
  {
    key: uuid(),
    label: '电话',
    prop: 'phone',
  },
]
const pagingParams = ref<any>({
  ...defaultPagingParams,
})

interface Enterprise {
  socialCreditCode: string
  name: string
  region: string
  subsidiaryType: any
  sortNumber: number
}

const enterpriseList = shallowRef<Enterprise[]>([])
const selected = shallowRef<string[]>([])
const currentUserId = ref<number>()

async function getUserList() {
  pagingParams.value.userName = userName.value
  const pagination = { ...toValue(pagingParams) }
  loading.value = true
  try {
    const { data } = await sysUserApi.queryList(
      pagination,
    )
    setUserList(data?.records ?? [])
    setTotal(data.total ?? 0)
  }
  finally {
    loading.value = false
  }
}

async function clickSearch() {
  pagingParams.value.pageNumber = 1
  pagingParams.value.userName = userName.value
  await nextTick()
  getUserList()
}

async function clickAssign(row: UserQueryListResult) {
  if (row.id) {
    currentUserId.value = row.id
    await nextTick()
    await getSelected(row.id)
    dialogRef.value?.open()
  }
}

async function clickSave(done: () => void) {
  try {
    const userId = unref(currentUserId)
    if (userId) {
      await saveSelected(userId, unref(selected).join(','))
      done()
      ElMessage.success('保存成功')
      await nextTick()
      dialogRef.value?.close()
    }
  }
  finally {
    done()
  }
}

// 查询企业配置的下拉列表
async function getEnterpriseListOfReport() {
  const { data } = await loadEnterpriseOfReportAll()
  enterpriseList.value = data || []
  return data
}

async function getSelected(userId: number) {
  const { data } = await loadSelectedEnterpriseOfReportUser(userId)
  const codes = data && data.socialCreditCodes ? data.socialCreditCodes.replace(/^,/, '').replace(/,$/, '') : ''
  selected.value = codes ? codes.split(',') : []
}
async function saveSelected(userId: number, code: string) {
  await saveReportUserSubsidiary(userId, code)
}

onMounted(() => {
  getEnterpriseListOfReport()
  getUserList()
})
</script>

<template>
  <div
    class="padding-sm flex-direction flex align-end container"
  >
    <view-table
      :columns="column"
      :loading="loading"
      :data="userList"
      :operate-width="200"
      :show-download="false"
    >
      <template #actions>
        <div class="flex items-center gap-1">
          <span>用户名：</span>
          <el-input
            v-model="userName"
            class="w-40"
            clearable
            placeholder="请输入名称查找"
          />
          <el-button type="primary" :icon="Search" @click="clickSearch">
            查询
          </el-button>
        </div>
      </template>
      <template #operate="{ row }">
        <el-button type="primary" size="small" @click="clickAssign(row)">
          分配企业
        </el-button>
      </template>
    </view-table>
    <!-- 分页 -->
    <ListsPagination
      v-model:page-num="pagingParams.pageNumber"
      v-model:page-size="pagingParams.pageSize"
      :total="total"
      @current-change="getUserList"
      @size-change="getUserList"
    />
    <CustomDialog
      ref="dialogRef"
      title="分配企业"
      width="640px"
      need-saving
      @confirm="clickSave"
    >
      <div class="h-70">
        <ElCheckboxGroup
          v-model="selected"
          class="flex flex-wrap"
        >
          <ElCheckbox
            v-for="item in enterpriseList"
            :key="item.socialCreditCode"
            :class="enterpriseList.length > 7 ? 'w-1/2 !mr-0' : 'w-full'"
            :label="item.name"
            :value="item.socialCreditCode"
          />
        </ElCheckboxGroup>
      </div>
    </CustomDialog>
  </div>
</template>
